//
//  ThorBaseManager.m
//  ThorWebViewSDK_Example
//
//  Created by panfei mao on 2019/1/19.
//  Copyright © 2019 panfei mao. All rights reserved.
//

#import "ThorBaseManager.h"
#import "UIDevice+MarsReachability.h"
#import "UIDevice+MarsHardWare.h"
#import "NSDictionary+MarsJSONString.h"
#import "MarsLocationManager.h"
#import <CoreMotion/CoreMotion.h>

@implementation ThorBaseManager

/** 埋点基础环境参数 */
+ (void)baseDeviceParamsCompleted:(GetBaseDeviceParamsCompledBlock)completedBlock{
    __block NSMutableDictionary *paramsDict = [NSMutableDictionary dictionary];
    //  创建组
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_queue_create("com.ConcurrentQueue", DISPATCH_QUEUE_CONCURRENT);
    //  进入组（进入组和离开组必须成对出现,否则会造成死锁）
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        //  设备类型
        NSString *deviceType = [UIDevice jk_platformString];
        [paramsDict setValue:deviceType forKey:@"devType"];
        //  操作系统
        [paramsDict setValue:@"iOS" forKey:@"devOS"];
        //  操作系统版本
        NSString *systemVersion = [UIDevice jk_systemVersion];
        [paramsDict setValue:systemVersion forKey:@"devOSVersion"];
        //  app版本
        [paramsDict setValue:@"100" forKey:@"appVersion"];
        //  设备号
        [paramsDict setValue:[[NSUUID UUID] UUIDString] forKey:@"devId"];
        // wifi名称
        NSString *wifiName = [UIDevice mars_wifiName];
        if (wifiName) {
            [paramsDict setValue:wifiName forKey:@"wifiName"];
        } else {
            [paramsDict setValue:@"" forKey:@"wifiName"];
        }
        // 路由器ip地址
        NSString *ipAddress = [UIDevice mars_localWiFiIPAddress];
        if (ipAddress) {
            [paramsDict setValue:ipAddress forKey:@"ipAddr"];
        } else {
            [paramsDict setValue:@"" forKey:@"ipAddr"];
        }
        // mac地址
        NSString *bssid = [UIDevice jk_macAddress];
        if (bssid) {
            [paramsDict setValue:bssid forKey:@"bssid"];
        } else {
            [paramsDict setValue:@"" forKey:@"bssid"];
        }
        // 手机存储量
        NSString *storage = [NSString stringWithFormat:@"%.2fG",([UIDevice jk_totalDiskSpaceBytes]/(1000*1000*1000.0))];
        [paramsDict setValue:storage forKey:@"storage"];
        // 手机已用存储量
        NSString *storageUsed = [NSString stringWithFormat:@"%.2fG",(([UIDevice jk_totalDiskSpaceBytes]-[UIDevice jk_freeDiskSpaceBytes])/(1000*1000*1000.0))];
        [paramsDict setValue:storageUsed forKey:@"storageUsed"];
        // 手机电量
        NSString *batteryQuantity = [UIDevice mars_getBatteryQuantity];
        [paramsDict setValue:batteryQuantity forKey:@"electricity"];
        // 手机是否充电
        BOOL isBatteryCharge = [UIDevice mars_isBatteryCharge];
        if (isBatteryCharge) {
            //  在充电
            [paramsDict setValue:@(1) forKey:@"isCharging"];
        } else {
            //  不在充电
            [paramsDict setValue:@(0) forKey:@"isCharging"];
        }
        // 查看手机是否越狱
        BOOL isJailbroken = [UIDevice mars_isJailbroken];
        if (isJailbroken) {
            //  越狱
            [paramsDict setValue:@(1) forKey:@"isRoot"];
        } else {
            //  没有越狱
            [paramsDict setValue:@(0) forKey:@"isRoot"];
        }
        //  渠道号
        [paramsDict setValue:@"bl_h5" forKey:@"channel"];
        
        dispatch_group_leave(group);
    });
    //  进入组
    dispatch_group_enter(group);
    dispatch_group_async(group, dispatch_get_main_queue(), ^{
        //  获取经纬度
        //  经度
        NSString *longitude = [MarsLocationManager mars_shareLocationManager].longitudeString;
        //  纬度
        NSString *latitude = [MarsLocationManager mars_shareLocationManager].latitudeString;
        if (longitude) {
            [paramsDict setValue:longitude forKey:@"coordinateX"];
        } else {
            [paramsDict setValue:@"" forKey:@"coordinateX"];
        }
        if (latitude) {
            [paramsDict setValue:latitude forKey:@"coordinateY"];
        } else {
            [paramsDict setValue:@"" forKey:@"coordinateY"];
        }
        dispatch_group_leave(group);
    });
    //  进入组
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        // 获取陀螺仪参数
        CMMotionManager *motionManager = [[CMMotionManager alloc] init];
        NSOperationQueue *motionQueue = [[NSOperationQueue alloc] init];
        if (motionManager.deviceMotionAvailable) {
            motionManager.deviceMotionUpdateInterval = 1.0;
            [motionManager startDeviceMotionUpdatesToQueue:motionQueue withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
                if (error){
                    // 停止获取陀螺仪数据
                    [motionManager stopDeviceMotionUpdates];
                } else {
                    //2. Gravity 获取手机的重力值在各个方向上的分量，根据这个就可以获得手机的空间位置，倾斜角度等
                    double gravityX = motion.gravity.x;
                    double gravityY = motion.gravity.y;
                    double gravityZ = motion.gravity.z;
                    [paramsDict setValue:[NSString stringWithFormat:@"%.3f", gravityX] forKey:@"gyroscopeX"];
                    [paramsDict setValue:[NSString stringWithFormat:@"%.3f", gravityY] forKey:@"gyroscopeY"];
                    [paramsDict setValue:[NSString stringWithFormat:@"%.3f", gravityZ] forKey:@"gyroscopeZ"];
#ifdef DEBUG
                    NSLog(@"倾斜角：gravityX=%.f,gravityY=%.f,gravityZ=%.f",gravityX,gravityY,gravityZ);
#endif
                    [motionManager stopDeviceMotionUpdates];
                }
                dispatch_group_leave(group);
            }];
        } else {
            dispatch_group_leave(group);
        }
    });
    //  任务组完成
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        // 回到主线程
        NSString *jsonSting = [paramsDict mars_JSONString];
        completedBlock(jsonSting);
    });
}

@end
